package com.mjfeed.controller;

import javax.servlet.http.HttpServletRequest;


import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import com.mjfeed.util.SpringContextUtils;

/**
 * Controller基类
 * @author zhaominglei
 *
 */
public class BaseController {
	public static final int WEB_DEFAULT_PAGE_SIZE = 50; // 默认每页记录数(web端)
	public static final int APP_DEFAULT_PAGE_SIZE = 10; // 默认每页记录数(移动端)
	/** 错误视图 */
	protected static final String ERROR_VIEW = "/common/error";
	
	/**
	 * 获取国际化消息
	 * 
	 * @param code
	 *            代码
	 * @param args
	 *            参数
	 * @return 国际化消息
	 */
	protected String message(String code, Object... args) {
		return SpringContextUtils.getMessage(code, args);
	}
	
	/**
	 * 获取访问端IP
	 * @return
	 */
	public String getRemoteIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	public String getBasePath(HttpServletRequest request) {
		StringBuilder basePath = new StringBuilder();
		basePath.append(request.getScheme()).append("://").append(request.getServerName()).append(":");
		basePath.append(request.getServerPort()).append(request.getContextPath()).append("/");
		return basePath.toString();
	}
	
	public void renderJson(HttpServletResponse response, Object object) {
		response.setContentType("text/html; charset=utf-8");
		ObjectMapper mapper = new ObjectMapper();
		try {
			mapper.writeValue(response.getWriter(), object);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
